﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 示例2
{
    public partial class Form1 : Form
    {
       
        private SqlConnection mycon;
        private SqlDataAdapter myada;
        private SqlCommand mycomd;
        private SqlCommandBuilder mycbd;
        private DataSet myset;
        public Form1()
        {
            InitializeComponent();
            mycon = new SqlConnection("Data Source=USERCHI-591JOGO;Initial Catalog=scool;Integrated Security=True");
            mycomd=new SqlCommand("select * from student",mycon);
            myada=new SqlDataAdapter();
            myada.SelectCommand=mycomd;
            mycbd=new SqlCommandBuilder(myada);
            myset=new DataSet();
            myada.TableMappings.Add("student","student");
            myada.TableMappings[0].ColumnMappings.Add("sno","学号");
            myada.TableMappings[0].ColumnMappings.Add("sname","姓名");
            myada.TableMappings[0].ColumnMappings.Add("sex","性别");
            myada.TableMappings[0].ColumnMappings.Add("birthday","生日");
            myada.TableMappings[0].ColumnMappings.Add("class","班级");
        }
        

       

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                myada.Update(myset.Tables["student"].GetChanges());
                MessageBox.Show("数据库修改成功","成功信息");
                myset.Tables["student"].AcceptChanges();
            }
            catch(SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
            private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                myada.Fill(myset,"student");
            }
                catch(SqlException ex)
            {
                MessageBox.Show(ex.ToString());

             }
                finally 
            {
                mycon.Close();
            }
                dataGridView1.DataSource=myset.Tables["student"].DefaultView;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("确定要删除当前数据？","",MessageBoxButtons.OKCancel)==DialogResult.OK)
            {
                try{
                myset.Tables[0].Rows[dataGridView1.CurrentRow.Index].Delete();
                myada.Update(myset.Tables[0].GetChanges());
                MessageBox.Show("数据删除成功");
                myset.Tables[0].AcceptChanges();
                   }
            catch(SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
            else 
            {
                myset.Tables[0].RejectChanges();
            }
    }
}}
